from copy import copy

import native

from util import *
from expand import *
from reduce import *

def run(system, userlib, main, debug=True):
  lex=copy(main)
  del lex['main']

  dyn={}

  code=main['main']['code']
  tree=tuplifyTree(lex, dyn, code)

#  tree=(lex, dyn, code)

  while not checkLiteral(tree):
    while isTreeExpandable(tree):
      if debug:
        printTree('expand', tree)
      tree=expandTree(system, userlib, tree)
      if debug:
        printTree('expanded', tree)
    if debug:
      print '-'*20
    while tree and isTreeReducible(tree):
      if debug:
        printTree('reduce', tree)
      tree=reduceTree(system, userlib, tree)
      if tree:
        if debug:
          printTree('reduced', tree)
    if debug:
      print '='*20

  if tree:
    if debug:
      printTree('result', tree)
  return tree
